<?php

class ITSEC_Malware_Admin {

	private
		$settings,
		$core,
		$module_path;

	function run( $core ) {

		$this->core        = $core;
		$this->settings    = get_site_option( 'itsec_malware' );
		$this->module_path = ITSEC_Lib::get_module_path( __FILE__ );

		add_action( 'itsec_add_admin_meta_boxes', array( $this, 'add_admin_meta_boxes' ) ); //add meta boxes to admin page
		add_action( 'itsec_admin_init', array( $this, 'initialize_admin' ) ); //initialize admin area
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) ); //enqueue scripts for admin page
		add_action( 'wp_ajax_itsec_malware_request_url_scan_ajax', array( $this, 'wp_ajax_itsec_malware_request_url_scan_ajax' ) ); //Execute manual homepage scan request
		add_action( 'wp_ajax_itsec_malware_get_scan_results_ajax', array( $this, 'wp_ajax_itsec_malware_get_scan_results_ajax' ) ); //Execute manual homepage scan report
		add_filter( 'itsec_add_dashboard_status', array( $this, 'dashboard_status' ) ); //add information for plugin status
		add_filter( 'itsec_tracking_vars', array( $this, 'tracking_vars' ) );
		add_filter( 'itsec_logger_displays', array( $this, 'itsec_logger_displays' ) ); //adds logs metaboxes

		//manually save options on multisite
		if ( is_multisite() ) {
			add_action( 'itsec_admin_init', array( $this, 'save_network_options' ) ); //save multisite options
		}

	}

	/**
	 * Add meta boxes to primary options pages
	 *
	 * @return void
	 */
	public function add_admin_meta_boxes() {

		$id    = 'malware_options';
		$title = __( 'Malware Scanning', 'it-l10n-better-wp-security' );

		add_meta_box(
			$id,
			$title,
			array( $this, 'metabox_malware_settings' ),
			'security_page_toplevel_page_itsec_settings',
			'advanced',
			'core'
		);

		$this->core->add_toc_item(
		           array(
			           'id'    => $id,
			           'title' => $title,
		           )
		);

	}

	/**
	 * Add malware admin Javascript
	 *
	 * @since 4.4
	 *
	 * @return void
	 */
	public function admin_enqueue_scripts() {

		global $itsec_globals;

		if ( isset( get_current_screen()->id ) && ( strpos( get_current_screen()->id, 'security_page_toplevel_page_itsec_settings' ) !== false || strpos( get_current_screen()->id, 'security_page_toplevel_page_itsec_logs' ) !== false ) ) {

			wp_enqueue_script( 'itsec_malware_js', $this->module_path . 'js/admin-malware.js', array( 'jquery' ), $itsec_globals['plugin_build'] );
			wp_localize_script(
				'itsec_malware_js',
				'itsec_malware',
				array(
					'module_path'          => $this->module_path,
					'button_text'          => __( 'Scan Homepage for Malware', 'it-l10n-better-wp-security' ),
					'scanning_button_text' => __( 'Scanning... (this could take a little while)', 'it-l10n-better-wp-security' ),
					'no_changes'           => __( 'No malware was detected.', 'it-l10n-better-wp-security' ),
					'changes'              => __( 'Malware has been detected. Please check the log page for details.', 'it-l10n-better-wp-security' ),
					'error'                => __( 'An error occured. Please try again later', 'it-l10n-better-wp-security' ),
					'nonce'                => wp_create_nonce( 'itsec_do_malware_scan' ),
					'screen'               => get_current_screen(),
		)
		);

		}

	}

	/**
	 * echos api key Field
	 *
	 * @since 4.4
	 *
	 * @return void
	 */
	public function api_key() {

		if ( isset( $this->settings['api_key'] ) ) {
			$api_key = sanitize_text_field( $this->settings['api_key'] );
		} else {
			$api_key = '';
		}

		echo '<input class="large-text" name="itsec_malware[api_key]" id="itsec_malware_api_key" value="' . $api_key . '" type="text">';
		echo '<label for="itsec_malware_api_key"> ' . __( 'You will need to get a free api key from ', 'it-l10n-better-wp-security' ) . ' <a href="https://www.virustotal.com" target="_blank">VirusTotal.com</a> ' . __( 'to use this feature.', 'it-l10n-better-wp-security' ) . '<br />' . __('For more information on setting up your account, visit this', 'it-l10n-better-wp-security' ) .  ' <a href="http://ithemes.com/security/how-to-malware-scan-api-key-with-virustotal/" target="_blank">VirusTotal API key tutorial</a>.</label>';
	}

	/**
	 * Sets the status in the plugin dashboard
	 *
	 * @since 4.4
	 *
	 * @param array $statuses array of statuses
	 *
	 * @return array array of statuses
	 */
	public function dashboard_status( $statuses ) {

		// @todo figure out a better check for scheduled scans
		if ( $this->settings['enabled'] === true && 1 == 1 ) {

			$status_array = 'safe-high';
			$status       = array( 'text' => __( 'Malware scanning is enabled and running at scheduled intervals on your computer', 'it-l10n-better-wp-security' ), 'link' => '#itsec_malware_enabled', );

		} elseif ( $this->settings['enabled'] === true ) {

			$status_array = 'medium';
			$status       = array( 'text' => __( 'Malware scanning is enabled but not scheduled. Consider enabling scheduled scans.', 'it-l10n-better-wp-security' ), 'link' => '#itsec_malware_enabled', );

		} else {

			$status_array = 'high';
			$status       = array( 'text' => __( 'Malware scanning is not enabled.', 'it-l10n-better-wp-security' ), 'link' => '#itsec_malware_enabled', );

		}

		array_push( $statuses[$status_array], $status );

		return $statuses;

	}

	/**
	 * echos Enable Strong Passwords Field
	 *
	 * @since 4.4
	 *
	 * @return void
	 */
	public function enabled() {

		if ( isset( $this->settings['enabled'] ) && $this->settings['enabled'] === true ) {
			$enabled = 1;
		} else {
			$enabled = 0;
		}

		$content = '<input type="checkbox" id="itsec_malware_enabled" name="itsec_malware[enabled]" value="1" ' . checked( 1, $enabled, false ) . '/>';
		$content .= '<label for="itsec_malware_enabled"> ' . __( 'Enable malware scanning.', 'it-l10n-better-wp-security' ) . '</label>';

		echo $content;

	}

	/**
	 * Execute admin initializations
	 *
	 * @return void
	 */
	public function initialize_admin() {

		//Add Settings sections
		add_settings_section(
			'malware-enabled',
			__( 'Enable Malware Scanning', 'it-l10n-better-wp-security' ),
			'__return_empty_string',
			'security_page_toplevel_page_itsec_settings'
		);

		add_settings_section(
			'malware-settings',
			__( 'Malware Scanning Settings', 'it-l10n-better-wp-security' ),
			'__return_empty_string',
			'security_page_toplevel_page_itsec_settings'
		);

		//Add Settings Fields
		add_settings_field(
			'itsec_malware[enabled]',
			__( 'Enable Malware Scanning', 'it-l10n-better-wp-security' ),
			array( $this, 'enabled' ),
			'security_page_toplevel_page_itsec_settings',
			'malware-enabled'
		);

		add_settings_field(
			'itsec_malware[api_key]',
			__( 'API Key', 'it-l10n-better-wp-security' ),
			array( $this, 'api_key' ),
			'security_page_toplevel_page_itsec_settings',
			'malware-settings'
		);

		//Register the settings field for the entire module
		register_setting(
			'security_page_toplevel_page_itsec_settings',
			'itsec_malware',
			array( $this, 'sanitize_module_input' )
		);

	}

	/**
	 * Array of metaboxes for the logs screen
	 *
	 * @since 4.4
	 *
	 * @param array $displays metabox array
	 *
	 * @return array metabox array
	 */
	public function itsec_logger_displays( $displays ) {

		//Don't attempt to display logs if brute force isn't enabled
		if ( isset( $this->settings['enabled'] ) && $this->settings['enabled'] === true ) {

			$displays[] = array(
				'module'   => 'malware',
				'title'    => __( 'Malware Scan', 'it-l10n-better-wp-security' ),
				'callback' => array( $this, 'logs_metabox_content' )
			);

		}

		return $displays;

	}

	/**
	 * Render the settings metabox
	 *
	 * @return void
	 */
	public function logs_metabox_content() {

		$this->malware_scan_form( 'logs' );

		if ( ! class_exists( 'ITSEC_Malware_Log' ) ) {
			require( dirname( __FILE__ ) . '/class-itsec-malware-log.php' );
		}

		$log_display = new ITSEC_Malware_Log();

		$log_display->prepare_items();
		$log_display->display();

	}

	/**
	 * Echos the one-time malware scan form
	 *
	 * @since 4.0
	 *
	 * @param string $origin the origin screen where the button was pressed
	 *
	 * @return void
	 */
	public function malware_scan_form( $origin ) {

		if ( isset( $this->settings['enabled'] ) && $this->settings['enabled'] === true ) {

			echo '<form id="itsec_one_time_malware_scan" method="post" action="">';
			echo wp_nonce_field( 'itsec_do_malware_scan', 'wp_nonce' );
			echo '<input type="hidden" name="itsec_malware_scan_origin" value="' . sanitize_text_field( $origin ) . '">';
			echo '<p>' . __( "Press the button below to scan your site's homepage for malware. Note that if malware is found this will take you to the logs page for details.", 'it-l10n-better-wp-security' ) . '</p>';
			echo '<p><input type="submit" id="itsec_one_time_malware_scan_submit" class="button-primary" value="' . __( 'Scan Homepage for Malware', 'it-l10n-better-wp-security' ) . '" /></p>';
			echo '</form>';
			echo '<div id="itsec_malware_scan_status"><p></p><a href="?page=toplevel_page_itsec_logs&itsec_log_filter=malware" class="button-secondary">' . __( 'View logs of previous scans', 'it-l10n-better-wp-security' ) . '</a></div>';

		}

	}

	/**
	 * Render the settings metabox
	 *
	 * @since 4.0
	 *
	 * @return void
	 */
	public function metabox_malware_settings() {

		echo $this->malware_scan_form( 'settings' );

		$this->core->do_settings_section( 'security_page_toplevel_page_itsec_settings', 'malware-enabled', false );
		$this->core->do_settings_section( 'security_page_toplevel_page_itsec_settings', 'malware-settings', false );

		echo '<p>' . PHP_EOL;

		settings_fields( 'security_page_toplevel_page_itsec_settings' );

		echo '<input class="button-primary" name="submit" type="submit" value="' . __( 'Save All Changes', 'it-l10n-better-wp-security' ) . '" />' . PHP_EOL;

		echo '</p>' . PHP_EOL;

	}

	/**
	 * Sanitize and validate input
	 *
	 * @param  Array $input array of input fields
	 *
	 * @return Array         Sanitized array
	 */
	public function sanitize_module_input( $input ) {

		//process strong passwords settings
		$input['enabled'] = ( isset( $input['enabled'] ) && intval( $input['enabled'] == 1 ) ? true : false );
		$input['api_key'] = ( isset( $input['api_key'] ) ? trim( sanitize_text_field( $input['api_key'] ) ) : '' );

		if ( $input['enabled'] === true && $input['api_key'] === '' ) {

			$type             = 'error';
			$message          = __( 'You must enter a valid API key to use the malware scanner.', 'it-l10n-better-wp-security' );
			$input['enabled'] = false;

			add_settings_error( 'itsec', esc_attr( 'settings_updated' ), $message, $type );

		}

		if ( is_multisite() ) {

			$this->core->show_network_admin_notice( false );

			$this->settings = $input;

		}

		return $input;

	}

	/**
	 * Prepare and save options in network settings
	 *
	 * @return void
	 */
	public function save_network_options() {

		if ( isset( $_POST['itsec_malware'] ) ) {

			if ( ! wp_verify_nonce( $_POST['_wpnonce'], 'security_page_toplevel_page_itsec_settings-options' ) ) {
				die( __( 'Security error!', 'it-l10n-better-wp-security' ) );
			}

			update_site_option( 'itsec_malware', $_POST['itsec_malware'] ); //we must manually save network options

		}

	}

	/**
	 * Adds fields that will be tracked for Google Analytics
	 *
	 * @since 4.0
	 *
	 * @param array $vars tracking vars
	 *
	 * @return array tracking vars
	 */
	public function tracking_vars( $vars ) {

		$vars['itsec_malware'] = array(
			'enabled' => '0:b',
		);

		return $vars;

	}

	/**
	 * Executes one-time malware result retrieval.
	 *
	 * @since 4.0
	 *
	 * @return void
	 */
	public function wp_ajax_itsec_malware_get_scan_results_ajax() {

		if ( ! wp_verify_nonce( sanitize_text_field( $_POST['nonce'] ), 'itsec_do_malware_scan_status' ) ) {
			die( __( 'Security error!', 'it-l10n-better-wp-security' ) );
		}

		$module = new ITSEC_Malware();
		$module->run();

		$response = $module->scan_report();

		if ( ! isset( $response['positives'] ) ) {

			$response['nonce'] = wp_create_nonce( 'itsec_do_malware_scan_status' );

		}

		header( 'Content-Type: application/json' );

		die( json_encode( $response ) );

	}

	/**
	 * Executes one-time malware scan.
	 *
	 * @since 4.0
	 *
	 * @return void
	 */
	public function wp_ajax_itsec_malware_request_url_scan_ajax() {

		if ( ! wp_verify_nonce( sanitize_text_field( $_POST['nonce'] ), 'itsec_do_malware_scan' ) ) {
			die( __( 'Security error!', 'it-l10n-better-wp-security' ) );
		}

		$module = new ITSEC_Malware();
		$module->run();

		$response = $module->one_time_scan();

		$response['nonce'] = wp_create_nonce( 'itsec_do_malware_scan_status' );

		header( 'Content-Type: application/json' );

		die( json_encode( $response ) );

	}

}